<script setup>
import {ref} from 'vue';
import {getTagList} from "@/api/tag.js";
import {closeToast, showLoadingToast} from "vant";
import {useTeamTagStore} from "@/stores/index.js";
import router from "@/router/index.js";

/**
 * 标签表单
 */
const tagForm = ref([]);
const updateTagForm = () => {
  tagForm.value = items.value.flatMap(group =>
    group.children.filter(child => activeIds.value.includes(child.id))
  )
}

/**
 * 标签选择
 * @type {Ref<UnwrapRef<number[]>, UnwrapRef<number[]> | number[]>}
 */
const activeIds = ref([])
const activeIndex = ref(0)
const items = ref([])

/**
 * 获取标签
 */
const getTags = () => {
  showLoadingToast({
    message: '加载中...',
    duration: 0,
    forbidClick: true,
  })
  getTagList().then(res => {
    if (res.data.code === 1) {
      items.value = res.data.data
      closeToast()
    }else {
      // eslint-disable-next-line no-undef
      showToast("获取标签失败，请稍后再试！")
    }
  }).catch(err => {
    console.log(err)
  })
}
getTags()

/**
 * 通过标签搜索
 */
const searchByTag = () => {
  if (tagForm.value.length === 0) {
    // eslint-disable-next-line no-undef
    showToast("请选择标签！")
    return
  }
  const tagStore = useTeamTagStore()
  tagStore.addTag(tagForm.value)
  router.replace({
    path: '/team/add'
  })
}

/**
 * 获取历史标签
 */
const getHistoryTags = () => {
  const tagStore = useTeamTagStore()
  const historyTags = tagStore.getAllTag()
  for (const tag of historyTags) {
    activeIds.value.push(tag.id)
  }
  tagForm.value = historyTags
}
getHistoryTags()

/**
 * 返回
 */
const clearTags = () => {
  activeIds.value.length = 0;
  const tagStore = useTeamTagStore();
  tagStore.removeAllTag()
  updateTagForm()
  router.replace({
    path: '/team/add'
  })
}
</script>

<template>
  <div class="team-page">
    <van-nav-bar
      fixed
      left-arrow
      left-text="返回并清空"
      placeholder
      right-text="就这些"
      title="为队伍增加标签"
      @click-left="clearTags"
      @click-right="searchByTag"
    />
    <div class="tag-container">
      <div class="tag-search">
        <span v-if="tagForm.length===0" class="tag-search-placeholder">在下方为队伍选择标签吧！</span>
        <span v-else class="tag">
          <van-tag v-for="tag in tagForm" :key="tag.id" class="tag-item" size="medium" type="primary">{{
              tag.text
            }}</van-tag>
        </span>
      </div>
    </div>
    <van-empty v-if="items.length===0" description="暂时没有标签哦~"/>
    <van-tree-select
      v-else
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="items"
      height="auto"
      @click-item="updateTagForm"
    />
  </div>
</template>

<style scoped>
.tag-container{
  padding: 10px;
  background-color: #ffffff;
}

.tag-search{
  background-color: #f1f1f1;
  padding: 2px;
  border-radius: 2px;
}

.tag-search .tag-search-placeholder, .tag-search .tag {
  height: 30px;
  line-height: 30px;
  color: #9e9e9e;
}

.tag-search .tag .tag-item {
  margin: 3px;
}
</style>
